package com.epidemy

import org.mortbay.jetty.handler.AbstractHandler
import javax.servlet.http.{HttpServletResponse, HttpServletRequest}
import org.mortbay.jetty.{Server, Request}

/*
UPnP:
http://teleal.org/projects/cling

Opening ports on router with DMZ :
http://hints.macworld.com/article.php?story=20051015142349372
*/
/// http://docs.codehaus.org/display/JETTY/Embedding+Jetty
class ClassServer {
  private val handler = new AbstractHandler()
  {
    override def handle(target: String, request: HttpServletRequest, response: HttpServletResponse, dispatch: Int) = {
      // TODO handle authentication

      val in = getClass.getClassLoader.getResourceAsStream(target)
      if (in != null) {
        println("Serving " + target)
        response.setContentType("application/octet-stream")
        response.setStatus(HttpServletResponse.SC_OK)
        val b = new Array[Byte](1024)
        val out = response.getOutputStream
        var l = 0
        while ({ l = in.read(b); l > 0 }) {
          out.write(b, 0, l)
        }
        in.close
      } else {
        println("Failed to serve " + target)
        response.setStatus(HttpServletResponse.SC_NOT_FOUND)
      }
      request.asInstanceOf[Request].setHandled(true)
    }
  };

  lazy val port = {
    var nextPort = 8081
    var started = false
    while (!started && nextPort <= 0xffff) {
      try {
        val server = new Server(nextPort)
        server.setHandler(handler)
        server.start
        started = true
      } catch {
        case _ =>
          nextPort += 1
      }
    }
    if (started) {
      println("Class server listening on port " + nextPort)
      Some(nextPort)
    } else {
      println("Failed to launch class server !")
      None
    }
  }
}
